<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    title="批量关联渠道SKU"
    width="800"
    draggable
    @close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :z-index="2000"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-align="right"
      label-width="100"
      size="default"
      label-position="top"
    >
      <el-row :gutter="21">
        <el-col :span="8">
          <el-form-item label="平台" prop="platform">
            <el-select
              v-model="form.platform"
              clearable
              placeholder="请选择"
              class="w-full"
              disabled
            >
              <el-option
                v-for="item in props.platformOptions"
                :key="item.platform_code"
                :label="item.platform_name"
                :value="item.platform_id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="店铺" prop="shop_id">
            <el-select
              v-model="form.shop_id"
              clearable
              placeholder="请选择"
              class="w-full"
              filterable
              @change="changeShop"
            >
              <el-option
                v-for="item in props.shopOptions"
                :key="item.shop_id"
                :label="item.shop_name"
                :value="item.shop_id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="销售人员" prop="operations_id">
            <select-personnel
              class="w-full"
              v-model="form.operations_id"
              placeholder="请选择销售人员"
              @change="changePersonel"
            ></select-personnel>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="操作运营人员" prop="operator_user_id">
            <select-personnel
              class="w-full"
              v-model="form.operator_user_id"
              placeholder="请选择操作运营人员"
            ></select-personnel>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div>
      系统SKU与渠道SKU管理
      <span class="text-red-500"
        >（从Excel中复制 或 以“Tab”制表符号分隔，一行一条记录） </span
      ><el-button @click="clearInfo">清空</el-button>
    </div>
    <div class="mb-4">
      <div class="flex">
        <div class="mr-8">系统SKU</div>
        <div>
          渠道SKU <span class="text-[#FF0000] ml-6">注：渠道SKU区分字母大小写</span>
        </div>
      </div>
      <div>
        <el-input
          v-model="form.sku_data"
          type="textarea"
          :autosize="{ minRows: 10, maxRows: 10 }"
          @keydown.tab.prevent="insertTab"
        ></el-input>
      </div>
    </div>
    <el-button type="primary" :loading="loading" @click="handleBatch"
      >批量关联渠道SKU</el-button
    >
    <div class="mt-4">
      <div>执行结果</div>
      <div class="border h-[250px] overflow-y-auto py-4 px-4">
        <div
          :class="[item.code == 1 ? 'text-red-500' : 'text-[#7dcc6f]']"
          v-for="(item, index) in messageInfo"
          :key="item"
        >
          {{ item.msg }}
        </div>
      </div>
    </div>
    <template #footer>
      <el-button @click="close">关闭</el-button>
    </template>
  </el-dialog>
</template>
<script setup name="batchRelevanceChannel" lang="jsx">
import { reactive, ref, toRefs } from "vue";
import SelectPlatformSite from "@/components/SelectPlatformSite";
import { ElMessage, ElMessageBox } from "element-plus";
import { batchChannelSave } from "../api/index.js";

const visible = ref(false);

const props = defineProps({
  shopOptions: {
    type: Array,
    default: () => [],
  },
  platformOptions: {
    type: Array,
    default: () => [],
  },
});
const data = reactive({
  limit: 0, // 最大文件上传数
  form: {},
  messageInfo: null,
  rules: {
    shop_id: [{ required: true, message: "请选择店铺", trigger: "change" }],
    platform: [{ required: true, message: "请选择平台" }],
    operations_id: [{ required: true, message: "请选择销售人员", trigger: "change" }],
    operator_user_id: [
      { required: true, message: "请选择操作运营人员", trigger: "change" },
    ],
  },
  load: false,
  loading: false,
});

const { limit, form, messageInfo, sku_data, rules, load, loading } = toRefs(data);

const open = async (val) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  form.value.platform = val;
  visible.value = true;
};

// 上传校验
const validator = (fileInfo) => {
  return (() => {})();
};

const emits = defineEmits(["query"]);

const changeShop = async (val) => {
  const item = props.shopOptions.find((i) => i.shop_id == val);
  form.value.shop_name = item?.shop_name;
};

// 捕获 Tab 键的按下事件
const insertTab = (event) => {
  const textarea = event.target;
  const start = textarea.selectionStart;
  const end = textarea.selectionEnd;
  form.value.sku_data =
    form.value.sku_data.substring(0, start) + "\t" + form.value.sku_data.substring(end);
  textarea.setSelectionRange(start + 1, start + 1);
};

const formRef = ref();

// 批量关联渠道SKU
const handleBatch = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (!form.value.sku_data) {
        ElMessage.error("请输入或者复制内容");
        return;
      }
      loading.value = true;
      let lines = form.value.sku_data.split("\n");
      const result = [];
      const massageArray = [];
      lines.forEach((item, index) => {
        let firstIndex = item.indexOf("\t");
        if (firstIndex !== -1) {
          let firstPart = item.substring(0, firstIndex);
          let secondPart = item.substring(firstIndex + 1);
          let firstError = firstPart.indexOf(" ");
          let secondError01 = secondPart.indexOf(" ");
          let secondError02 = secondPart.indexOf("\t");
          if (firstError != -1) {
            massageArray.push(`第${index + 1}行，系统SKU格式错误`);
          }
          if (secondError01 != -1 || secondError02 != -1) {
            massageArray.push(`第${index + 1}行，渠道SKU格式错误`);
          }
          result.push({
            goods_sku: firstPart,
            platform_sku: secondPart,
          });
        } else if (item) {
          result.push({
            goods_sku: item,
            platform_sku: "",
          });
          massageArray.push(`第${index + 1}行，格式错误`);
        }
      });

      const formData = Object.assign(
        {},
        {
          ...form.value,
          sku_data: result,
        }
      );
      try {
        const res = await batchChannelSave(formData);
        messageInfo.value = res.data;
      } catch (e) {
        throw Error(e);
      } finally {
        loading.value = false;
      }
    }
  });
};

const clearInfo = () => {
  form.value.sku_data = "";
  messageInfo.value = [];
};

const close = () => {
  form.value = {};
  messageInfo.value = [];
  visible.value = false;
};

const changePersonel = () => {
  if (!form.value.operator_user_id) {
    form.value.operator_user_id = form.value.operations_id;
  }
};

defineExpose({ open });
</script>
<style lang="scss" scoped></style>
